package com.manger.common.tcp.client;

import com.manger.common.tcp.decode.impl.BusinessDecode;
import com.manger.common.utils.SocketByteConvertUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;

public class TcpClient {

    private ChannelFuture future;

    private static LinkedBlockingQueue<BusinessDecode> receiptQueue = new LinkedBlockingQueue<BusinessDecode>();

    private TcpClient() {

    }

    private static TcpClient instance = new TcpClient();

    public static TcpClient getInstance() {
        return instance;
    }

    public void connect(String ip, int port) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            /**客户端相关配置信息*/
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new TcpClientChannel());

            future = bootstrap.connect(ip, port).sync();
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            workerGroup.shutdownGracefully();
        }
    }

    public static LinkedBlockingQueue<BusinessDecode> getReceiptQueue() {
        return receiptQueue;
    }

    public static void setReceiptQueue(LinkedBlockingQueue<BusinessDecode> receiptQueue) {
        TcpClient.receiptQueue = receiptQueue;
    }

    public void send(byte[] data) {
        future.channel().writeAndFlush(data);
    }

    public static void main(String[] args) throws Exception {
        String filePath = System.getProperty("user.dir") + "/" + "config.properties";
        System.out.println(filePath);
        File file = new File(filePath);
        if(!file.exists()){
            System.out.println("没有找到配置文件！【config.properties】");
            return;
        }
        Properties properties = new Properties();
        properties.load(new FileInputStream(file));

        TcpClient tcpClient = TcpClient.getInstance();
        tcpClient.connect(properties.getProperty("tcp.server.ip"), Integer.valueOf(properties.getProperty("tcp.server.port")));
    }
}
